package com.imonsoft.sqm.service.excel.BaseExcel;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.ReturnMessage;
import com.imonsoft.common.util.StringUtil;

/**
 * 
 * 
 * @author zhowei
 * @since JDK1.6
 * @version 1.0
 */
@Service("excelService")
public class ExcelServiceImpl implements Serializable, ExcelService {

	/**
	 * 日志
	 */
	private Logger logger = Logger.getLogger(ExcelServiceImpl.class);

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1059354301224190157L;

	@Override
	public ReturnMessage loadExcelModel(HttpServletRequest request, HttpServletResponse response, String excelName) {
		FileInputStream is = null;
		OutputStream os = null;
		ReturnMessage message = new ReturnMessage();
		try {
			message.setSuccess(true);
			os = response.getOutputStream(); // 创建流
			byte[] buf = new byte[8192];
			int len = 0;
			is = new FileInputStream(request.getSession().getServletContext().getRealPath("/excelModel/") + "/" + excelName);
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/vnd.ms-excel"); // 格式为EXCEL
			response.setHeader("content-disposition", "attachment; filename=" + excelName);
			while ((len = is.read(buf)) != -1) {
				os.write(buf, 0, len);
			}
			is.close();
			os.close();
		} catch (Exception e) {
			message.setMsg(e.getMessage());
			message.setSuccess(false);
			logger.info("工具类====Excel操作解析Excel方法异常====EXEC 类名：ExcelDccUtils EXEC 方法名：loadExcelModel ====ERROR:模版下载失败" + e.getMessage());
		} finally {
			try {
				if (is != null) {
					is.close();
					message.setMsg("流关闭失败");
				}
				if (os != null) {
					os.close();
					message.setMsg("流关闭失败");
				}
			} catch (Exception e) {
				message.setSuccess(false);
			}
			if (message.isSuccess()) {
				message.setMsg("模版下载成功!");
			}
		}
		return message;
	}

	public List<Object[]> readExcel(InputStream in,int maxSize, int startRow) throws Exception {
		Workbook workbook = null;
		Sheet sheet = null;
		try {
			try {
				workbook = Workbook.getWorkbook(in);
			} catch (SystemException e) {
				throw new SystemException("Excel文件格式错误，请检查!");
			}

			Sheet[] sheets = workbook.getSheets();
			sheet = sheets[0];
			if (sheet.getRows() <= startRow) {
				throw new SystemException("Excel文件为空文件，请检查!");
			}

			List<Object[]> result = new ArrayList<Object[]>();
			for (int rowIndex = startRow; rowIndex < sheet.getRows(); rowIndex++) {
				Cell[] cells = sheet.getRow(rowIndex);
				Object[] row = new Object[101];

				row[0] = rowIndex + 1;
				for (int columnIndex = 0; columnIndex < ((cells.length >= 100) ? 100 : cells.length); columnIndex++) {
					row[columnIndex + 1] = cells[columnIndex].getContents();
				}
				boolean isEmpty = true;
				for (int i = 1; i < row.length; i++) {
					if (!StringUtil.isEmpty((String) row[i])) {
						isEmpty = false;
						break;
					}
				}
				if (isEmpty) {
					break;
				}
				result.add(row);
			}
			if(result!=null&&result.size()>0){
				if(result.size()>maxSize){
					throw new SystemException("文件最大不能超过"+maxSize+"条");
				}
			}
			return result;
		} finally {
			if (null != workbook)
				workbook.close();
			if (null != in)
				in.close();
		}
	}
	public List<Object[]> readExcelByModel(InputStream in,int maxSize, int startRow,int endRow) throws Exception {
		Workbook workbook = null;
		Sheet sheet = null;
		try {
			try {
				workbook = Workbook.getWorkbook(in);
			} catch (Exception e) {
				throw new Exception("Excel文件格式错误，请检查!");
			}

			Sheet[] sheets = workbook.getSheets();
			sheet = sheets[0];
			if (sheet.getRows() <= startRow) {
				throw new Exception("Excel文件为空文件，请检查!");
			}

			List<Object[]> result = new ArrayList<Object[]>();
			for (int rowIndex = startRow; rowIndex < endRow; rowIndex++) {
				Cell[] cells = sheet.getRow(rowIndex);
				Object[] row = new Object[101];

				row[0] = rowIndex + 1;
				for (int columnIndex = 0; columnIndex < ((cells.length >= 100) ? 100 : cells.length); columnIndex++) {
					row[columnIndex + 1] = cells[columnIndex].getContents();
				}
				boolean isEmpty = true;
				for (int i = 1; i < row.length; i++) {
					if (!StringUtil.isEmpty((String) row[i])) {
						isEmpty = false;
						break;
					}
				}
				if (isEmpty) {
					break;
				}
				result.add(row);
			}
			if(result!=null&&result.size()>0){
				if(result.size()>maxSize){
					throw new SystemException("文件最大不能超过"+maxSize+"条");
				}
			}
			return result;
		} finally {
			if (null != workbook)
				workbook.close();
			if (null != in)
				in.close();
		}
	}
	@Override
	public ReturnMessage loadPdf(HttpServletRequest request, HttpServletResponse response, String excelName) {
		FileInputStream is = null;
		OutputStream os = null;
		ReturnMessage message = new ReturnMessage();
		try {
			message.setSuccess(true);
			os = response.getOutputStream(); // 创建流
			byte[] buf = new byte[8192];
			int len = 0;
			is = new FileInputStream(request.getSession().getServletContext().getRealPath("/excelModel/") + "/" + excelName);
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/pdf");
			response.setHeader("content-disposition", "attachment; filename=" + excelName);
			while ((len = is.read(buf)) != -1) {
				os.write(buf, 0, len);
			}
			is.close();
			os.close();
		} catch (Exception e) {
			message.setMsg(e.getMessage());
			message.setSuccess(false);
			logger.info("工具类====Excel操作解析Excel方法异常====EXEC 类名：ExcelDccUtils EXEC 方法名：loadExcelModel ====ERROR:模版下载失败" + e.getMessage());
		} finally {
			try {
				if (is != null) {
					is.close();
					message.setMsg("流关闭失败");
				}
				if (os != null) {
					os.close();
					message.setMsg("流关闭失败");
				}
			} catch (Exception e) {
				message.setSuccess(false);
			}
			if (message.isSuccess()) {
				message.setMsg("模版下载成功!");
			}
		}
		return message;
	}
}
